home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1997 May / EnigmA AMIGA RUN 18 (1997)(G.R. Edizioni)(IT)[!][issue 1997-05][EAR-CD II].iso / ghost / gs403src_png.lha / gs4.03 / libpng / libpng.txt < prev    next >
Text File  |  1996-06-05  |  60KB  |  1,302 lines

  1. libpng.txt - a description on how to use and modify libpng
  2.  
  3.     libpng 1.0 beta 3 - version 0.89
  4.     Updated and distributed by Andreas Dilger <adilger@enel.ucalgary.ca>,
  5.        based on:
  6.  
  7.     libpng 1.0 beta 2 - version 0.88
  8.     For conditions of distribution and use, see copyright notice in png.h
  9.     Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  10.     May 24, 1996
  11.     Updated/rewritten per request in the libpng FAQ
  12.     Copyright (c) 1995 Frank J. T. Wojcik
  13.     December 18, 1995 && January 20, 1996
  14.  
  15. I. Introduction
  16.  
  17. This file describes how to use and modify the PNG reference library
  18. (known as libpng) for your own use.  There are five sections to this
  19. file: introduction, structures, reading, writing, and modification and
  20. configuration notes for various special platforms.  In addition to this
  21. file, example.c is a good starting point for using the library, as
  22. it is heavily commented and should include everything most people
  23. will need.
  24.  
  25. Libpng was written as a companion to the PNG specification, as a way
  26. to reduce the amount of time and effort it takes to support the PNG
  27. file format in application programs.  Most users will not have to
  28. modify the library significantly; advanced users may want to modify it
  29. more.  All attempts were made to make it as complete as possible,
  30. while keeping the code easy to understand.  Currently, this library
  31. only supports C.  Support for other languages is being considered.
  32.  
  33. Libpng has been designed to handle multiple sessions at one time,
  34. to be easily modifiable, to be portable to the vast majority of
  35. machines (ANSI, K&R, 16 bit, 32 bit) available, and to be easy to
  36. use.  The ultimate goal of libpng is to promote the acceptance of
  37. the PNG file format in whatever way possible.  While there is still
  38. work to be done (see the pngtodo.txt file), libpng should cover the
  39. majority of the needs of it's users.
  40.  
  41. Libpng uses zlib for its compression and decompression of PNG files.
  42. The zlib compression utility is a general purpose utility that is
  43. useful for more than PNG files, and can be used without libpng.
  44. See the documentation delivered with zlib for more details.
  45.  
  46. Libpng is thread safe, provided the threads are using different
  47. instances of the structures.  Each thread should have its own
  48. png_struct and png_info instances, and thus its own image.
  49. Libpng does not protect itself against two threads using the
  50. same instance of a structure.
  51.  
  52.  
  53.  
  54. II. Structures
  55.  
  56. There are two main structures that are important to libpng, png_struct
  57. and png_info.  The first, png_struct, is an internal structure that
  58. will not, for the most part, be used by a user except as the first
  59. variable passed to every png function call.
  60.  
  61. The png_info structure is designed to provide information about the
  62. png file.  All of its fields are intended to be examined or modified
  63. by the user.  See png.h for a good description of the png_info fields.
  64. png.h is also an invaluable reference for programming with libpng.
  65.  
  66. And while I'm on the topic, make sure you include the png header file:
  67.  
  68. #include <png.h>
  69.  
  70.  
  71.  
  72. III. Reading
  73.  
  74. Reading PNG files:
  75.  
  76. We'll now walk you through the possible functions to call when reading
  77. in a PNG file, briefly explaining the syntax and purpose of each one.
  78. See example.c and png.h for more detail.  While Progressive reading
  79. is covered in the next section, you will still need some of the
  80. functions discussed in this section to read a PNG file.
  81.  
  82. You will want to do the I/O initialization(*) before you get into libpng,
  83. so if it doesn't work, you don't have much to undo.  Of course, you
  84. will also want to insure that you are, in fact, dealing with a PNG
  85. file.  Libpng provides a simple check to see if a file is a PNG file.
  86. To use it, pass in the first 1 to 8 bytes of the file, and it will
  87. return true or false (1 or 0) depending on whether the bytes could be
  88. part of a PNG file.  Of course, the more bytes you pass in, the
  89. greater the accuracy of the prediction.  If you pass in more then
  90. eight bytes, libpng will only look at the first eight bytes.  However,
  91. because libpng automatically checks the file header, this is not often
  92. necessary, and you should pass a newly opened file pointer to libpng
  93. when reading a file.
  94.  
  95. (*): If you are not using the standard I/O functions, you will need
  96. to replace them with custom functions.  See the discussion under
  97. Customizing libpng.
  98.  
  99.     FILE *fp = fopen(file_name, "rb");
  100.     if (!fp)
  101.     {
  102.         return;
  103.     }
  104.     fread(header, 1, number, fp);
  105.     is_png = png_check_sig(header, number);
  106.     if (!is_png)
  107.     {
  108.         return;
  109.     }
  110.     fclose(fp);
  111.  
  112. Next, png_struct and png_info need to be allocated and initialized.
  113. In order to ensure that the size of these structures is correct even
  114. with a dynamically linked libpng, there are functions to initialize
  115. and allocate the structures.  We also pass the library version, and
  116. optionally pointers to error handling functions (these can be NULL
  117. if the default error handlers are to be used).  See the section on
  118. Changes to Libpng below regarding the old initialization functions.
  119.  
  120.     png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  121.        (void *)user_error_ptr, user_error_fn, user_warning_fn);
  122.     if (!png_ptr)
  123.         return;
  124.     png_infop info_ptr = png_create_info_struct(png_ptr);
  125.     if (!info_ptr)
  126.     {
  127.         png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
  128.         return;
  129.     }
  130.     png_infop end_info = png_create_info_struct(png_ptr);
  131.     if (!end_info)
  132.     {
  133.         png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
  134.         return;
  135.     }
  136.  
  137. The error handling routines passed to png_create_read_struct()
  138. are only necessary if you are not using the libpng supplied
  139. error handling functions.  When libpng encounters an error,
  140. it expects to longjmp back to your routine.  Therefore, you
  141. will need to call setjmp and pass the jmpbuf field of your
  142. png_struct.  If you read the file from different routines, you
  143. will need to update the jmpbuf field every time you enter a new
  144. routine that will call a png_ function.  See your documentation
  145. of setjmp/longjmp for your compiler for more information on
  146. setjmp/longjmp.  See the discussion on libpng error handling
  147. in the Customizing Libpng section below for more information on
  148. the libpng error handling.  If an error occurs, and libpng
  149. longjmp's back to your setjmp, you will want to call
  150. png_destroy_read_struct() to free any memory.
  151.  
  152.     if (setjmp(png_ptr->jmpbuf))
  153.     {
  154.         png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  155.         fclose(fp);
  156.         return;
  157.     }
  158.  
  159. Now you need to set up the input code.  The default for libpng is to
  160. use the C function fread().  If you use this, you will need to pass a
  161. valid FILE * in the function png_init_io().  Be sure that the file is
  162. opened in binary mode.  Again, if you wish to handle reading data in
  163. another way, see the discussion on libpng I/O handling in the Customizing
  164. Libpng section below.
  165.  
  166.     png_init_io(png_ptr, fp);
  167.  
  168. You are now ready to read all the file information up to the actual
  169. image data.  You do this with a call to png_read_info().
  170.  
  171.    png_read_info(png_ptr, info_ptr);
  172.  
  173. The png_info structure is now filled in with all the data necessary
  174. to read the file.  Some of the more important parts of the info_ptr are:
  175.  
  176.     width          - holds the width of the file
  177.     height         - holds the height of the file
  178.     bit_depth      - holds the bit depth of one of the image channels
  179.     color_type     - describes the channels and what they mean
  180.                      (see the PNG_COLOR_TYPE_ macros for more information)
  181.     channels       - number of channels of info for the color type
  182.     pixel_depth    - bits per pixel, the result of multiplying the 
  183.                      bit_depth times the channels
  184.     rowbytes       - number of bytes needed to hold a row
  185.     interlace_type - currently 0 for none, 1 for interlaced
  186.     valid          - this details which optional chunks were found in the
  187.                      file to see if a chunk was present, AND '&' valid with
  188.                      the appropriate PNG_INFO_<chunk name> define.
  189.  
  190. These are also important, but their validity depends on whether a
  191. corresponding chunk exists. Use valid (see above) to ensure that what
  192. you're doing with these values makes sense.
  193.  
  194.     palette        - the palette for the file (PNG_INFO_PLTE)
  195.     num_palette    - number of entries in the palette
  196.     gamma          - the gamma the file is written at (PNG_INFO_gAMA)
  197.     sig_bit        - the number of significant bits (PNG_INFO_sBIT)
  198.                      for the gray, red, green, and blue channels, whichever
  199.                      are appropriate for the given color type.
  200.     trans_values   - transparent pixel for non-paletted images (PNG_INFO_tRNS)
  201.     trans          - array of transparent entries for paletted images
  202.     num_trans      - number of transparent entries
  203.     hist           - histogram of palette (PNG_INFO_hIST)
  204.     mod_time       - time image was last modified (PNG_VALID_tIME)
  205.     background     - background color (PNG_VALID_bKGD)
  206.     text           - text comments in the file.
  207.     num_text       - number of comments
  208.  
  209. for more information, see the png_info definition in png.h and the
  210. PNG specification for chunk contents.  Be careful with trusting
  211. rowbytes, as some of the transformations could increase the space
  212. needed to hold a row (expand, RGBX, XRGB, gray_to_rgb, etc.).
  213. See png_update_info(), below.
  214.  
  215. A quick word about text and num_text.  PNG stores comments in
  216. keyword/text pairs, one pair per chunk.  While there are suggested
  217. keywords, there is no requirement to restrict the use to these
  218. strings.  There is a requirement to have at least one character for a
  219. keyword.  It is strongly suggested that keywords be sensible to humans
  220. (that's the point), so don't use abbreviations.  See the png
  221. specification for more details.  There is also no requirement to have
  222. text after the keyword.
  223.  
  224. Keywords should be limited to 80 characters without leading or trailing
  225. spaces, but non-consecutive spaces are allowed within the keyword.  It is
  226. possible to have the same keyword any number of times.  The text field
  227. is an array of png_text structures, each holding pointer to a keyword
  228. and a pointer to a text string.  Only the text string may be null.
  229. The keyword/text pairs are put into the array in the order that
  230. they are received.  However, some or all of the text chunks may be
  231. after the image, so, to make sure you have read all the text chunks,
  232. don't mess with these until after you read the stuff after the image.
  233. This will be mentioned again below in the discussion that goes with
  234. png_read_end().
  235.  
  236. After you've read the file information, you can set up the library to
  237. handle any special transformations of the image data.  The various
  238. ways to transform the data will be described in the order that they
  239. should occur.  This is important, as some of these change the color
  240. type and/or bit depth of the data, and some others only work on
  241. certain color types and bit depths.  Even though each transformation
  242. checks to see if it has data that it can do somthing with, you should
  243. make sure to only enable a transformation if it will be valid for the
  244. data.  For example, don't swap red and blue on grayscale data.
  245.  
  246. Data will be decoded into the supplied row buffers packed into bytes
  247. unless the library has been told to transform it into another format.
  248. For example, 4 bit/pixel paletted or grayscale data will be returned
  249. 2 pixels/byte with the leftmost pixel in the high-order bits of the
  250. byte, unless png_set_packing() is called.  8-bit RGB data will be stored
  251. in RGBRGBRGB format unless png_set_filler() is called to insert filler
  252. bytes, either before or after each RGB triplet.  16-bit RGB data will
  253. be returned RRGGBBRRGGBB, with the most significant byte of the color
  254. value first, unless png_set_strip_16() is called to transform it to
  255. regular RGBRGB triplets.
  256.  
  257. The following code transforms grayscale images of less than 8 to 8 bits,
  258. changes paletted images to RGB, and adds a full alpha channel if there is
  259. transparency information in a tRNS chunk.  This is most useful on
  260. grayscale images with bit depths of 2 or 4 or if there is a multiple-image
  261. viewing application that wishes to treat all images in the same way.
  262.  
  263.    if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  264.       info_ptr->bit_depth < 8)
  265.         png_set_expand(png_ptr);
  266.  
  267.     if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY &&
  268.       info_ptr->bit_depth < 8)
  269.       png_set_expand(png_ptr);
  270.  
  271.    if (info_ptr->valid & PNG_INFO_tRNS)
  272.       png_set_expand(png_ptr);
  273.  
  274. PNG can have files with 16 bits per channel.  If you only can handle
  275. 8 bits per channel, this will strip the pixels down to 8 bit.
  276.  
  277.    if (info_ptr->bit_depth == 16)
  278.       png_set_strip_16(png_ptr);
  279.  
  280. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  281. they can, resulting in, for example, 8 pixels per byte for 1 bit
  282. files.  This code expands to 1 pixel per byte without changing the
  283. values of the pixels:
  284.  
  285.     if (info_ptr->bit_depth < 8)
  286.         png_set_packing(png_ptr);
  287.  
  288. PNG files have possible bit depths of 1, 2, 4, 8, and 16.  It is then
  289. required that values be "scaled" or "shifted" up to the bit depth used
  290. in the file (ie from 5 bits/sample in the range [0,31] to 8 bits/sample
  291. in the range [0, 255]).  However, they also provide a way to describe
  292. the true bit depth of the image.  See the PNG specification for details.
  293. This call reduces the pixels back down to the true bit depth:
  294.  
  295.     if (info_ptr->valid & PNG_INFO_sBIT)
  296.         png_set_shift(png_ptr, &(info_ptr->sig_bit));
  297.  
  298. PNG files store 3 color pixels in red, green, blue order.  This code
  299. changes the storage of the pixels to blue, green, red:
  300.  
  301.     if (info_ptr->color_type == PNG_COLOR_TYPE_RGB ||
  302.         info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  303.         png_set_bgr(png_ptr);
  304.  
  305. PNG files store RGB pixels packed into 3 bytes. This code expands them
  306. into 4 bytes for windowing systems that need them in this format:
  307.  
  308.    if (info_ptr->bit_depth == 8 &&
  309.       info_ptr->color_type == PNG_COLOR_TYPE_RGB)
  310.       png_set_filler(png_ptr, filler_byte, PNG_FILLER_BEFORE);
  311.  
  312. where filler_byte is the number to fill with, and the location is
  313. either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
  314. you want the filler before the RGB or after.
  315.  
  316. For some uses, you may want a gray-scale image to be represented as
  317. RGB.  This code will do that conversion:
  318.  
  319.    if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY ||
  320.       info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  321.          png_set_gray_to_rgb(png_ptr);
  322.  
  323. The following code handles alpha and transparency by replacing it with
  324. a background value.  If there was a valid bKGD in the file, you can use
  325. it if you want.  However, you can replace it with your own if you want
  326. also.  If there wasn't one in the file, you must supply a color.  If
  327. libpng is doing gamma correction, you will need to tell libpng where
  328. the background came from so it can do the appropriate gamma
  329. correction.  If you have a grayscale and you are using png_set_expand()
  330. to change to a higher bit-depth you must indicate if the background gray
  331. needs to be expanded to the new bit-depth.  Similarly, if you are reading
  332. a paletted image, you must indicate if you have supplied the background
  333. index that needs to be expanded to RGB values.  You can always specify
  334. RGB color values directly when setting your background for paletted images.
  335.  
  336.    png_color_16 my_background;
  337.  
  338.    if (info_ptr->valid & PNG_INFO_bKGD)
  339.       png_set_backgrond(png_ptr, &(info_ptr->background),
  340.             PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
  341.    else
  342.       png_set_background(png_ptr, &my_background,
  343.          PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
  344.  
  345. The following code handles gamma transformations of the data.  Pass
  346. both the file gamma and the desired screen gamma.  If the file does
  347. not have a gamma value, you can pass one anyway if you wish.  Note
  348. that file gammas are inverted from screen gammas.  See the discussions
  349. on gamma in the PNG specification for more information.  It is
  350. strongly recommended that viewers support gamma correction.
  351.  
  352.    if (info_ptr->valid & PNG_INFO_gAMA)
  353.       png_set_gamma(png_ptr, screen_gamma, info_ptr->gamma);
  354.    else
  355.       png_set_gamma(png_ptr, screen_gamma, 0.45);
  356.  
  357. If you need to reduce an RGB file to a paletted file, or if a paletted
  358. file has more entries then will fit on your screen, png_set_dither()
  359. will do that.  Note that this is a simple match dither that merely
  360. finds the closest color available.  This should work fairly well with
  361. optimized palettes, and fairly badly with linear color cubes.  If you
  362. pass a palette that is larger then maximum_colors, the file will
  363. reduce the number of colors in the palette so it will fit into
  364. maximum_colors.  If there is a histogram, it will use it to make
  365. more intelligent choices when reducing the palette.  If there is no
  366. histogram, it may not do as good a job.
  367.  
  368.    if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  369.    {
  370.       if (info_ptr->valid & PNG_INFO_PLTE)
  371.       {
  372.          png_set_dither(png_ptr, info_ptr->palette,
  373.             info_ptr->num_palette, max_screen_colors,
  374.             info_ptr->histogram, 1);
  375.       }
  376.       else
  377.       {
  378.          png_color std_color_cube[MAX_SCREEN_COLORS] =
  379.             { ... colors ... };
  380.  
  381.          png_set_dither(png_ptr, std_color_cube, MAX_SCREEN_COLORS,
  382.             MAX_SCREEN_COLORS, NULL,0);
  383.       }
  384.    }
  385.  
  386. PNG files describe monochrome as black being zero and white being one.
  387. The following code will reverse this (make black be one and white be
  388. zero):
  389.  
  390.    if (info_ptr->bit_depth == 1 &&
  391.       info_ptr->color_type == PNG_COLOR_GRAY)
  392.       png_set_invert_mono(png_ptr);
  393.  
  394. PNG files store 16 bit pixels in network byte order (big-endian,
  395. ie. most significant bits first).  This code chages the storage to the
  396. other way (little-endian, ie. least significant bits first, eg. the
  397. way PCs store them):
  398.  
  399.     if (info_ptr->bit_depth == 16)
  400.         png_set_swap(png_ptr);
  401.  
  402. The last thing to handle is interlacing; this is covered in detail below,
  403. but you must call the function here.
  404.  
  405.    if (info_ptr->interlace_type)
  406.       number_passes = png_set_interlace_handling(png_ptr);
  407.  
  408. After setting the transformations, libpng can update your png_info
  409. structure to reflect any transformations you've requested with this
  410. call.  This is most useful to update the info structures rowbytes
  411. field, so you can use it to allocate your image memory.  This function
  412. will also update your palette with the correct display gamma and
  413. background if these have been given with the calls above.
  414.  
  415.     png_read_update_info(png_ptr, info_ptr);
  416.  
  417. After you call png_read_update_info(), you can allocate any
  418. memory you need to hold the image.  The row data is simply
  419. raw byte data for all forms of images.  As the actual allocation
  420. varies among applications, no example will be given.  If you
  421. are allocating one large chunk, you will need to build an
  422. array of pointers to each row, as it will be needed for some
  423. of the functions below.
  424.  
  425. After you've allocated memory, you can read the image data.
  426. The simplest way to do this is in one function call.  If you are
  427. allocating enough memory to hold the whole image, you can just
  428. call png_read_image() and libpng will read in all the image data
  429. and put it in the memory area supplied.  You will need to pass in
  430. an array of pointers to each row.
  431.  
  432. This function automatically handles interlacing, so you don't need
  433. to call png_set_interlace_handling() or call this function multiple
  434. times, or any of that other stuff necessary with png_read_rows().
  435.  
  436.    png_read_image(png_ptr, row_pointers);
  437.  
  438. where row_pointers is:
  439.  
  440.    png_bytep row_pointers[height];
  441.  
  442. You can point to void or char or whatever you use for pixels.
  443.  
  444. If you don't want to read int the whole image at once, you can
  445. use png_read_rows() instead.  If there is no interlacing (check
  446. info_ptr->interlace_type), this is simple:
  447.  
  448.     png_read_rows(png_ptr, row_pointers, NULL, number_of_rows);
  449.  
  450. where row_pointers is the same as in the png_read_image() call.
  451.  
  452. If you are doing this just one row at a time, you can do this with
  453. row_pointers:
  454.  
  455.     png_bytep row_pointers = row;
  456.     png_read_row(png_ptr, &row_pointers, NULL);
  457.  
  458. If the file is interlaced (info_ptr->interlace_type != 0), things get
  459. somewhat harder.  The only currently (as of 6/96 -- PNG
  460. Specification version 1.0) defined interlacing scheme for PNG files
  461. (info_ptr->interlace_type == 1) is a someewhat complicated 2D interlace
  462. scheme, known as Adam7, that breaks down an image into seven smaller
  463. images of varying size, based on an 8x8 grid.
  464.  
  465. libpng can fill out those images or it can give them to you "as is".
  466. If you want them filled out, there are two ways to do that.  The one
  467. mentioned in the PNG specification is to expand each pixel to cover
  468. those pixels that have not been read yet.  This results in a blocky
  469. image for the first pass, which gradually smoothes out as more pixels
  470. are read.  The other method is the "sparkle" method, where pixels are
  471. draw only in their final locations, with the rest of the image remaining
  472. whatever colors they were initialized to before the start of the read.
  473. The first method usually looks better, but tends to be slower, as there
  474. are more pixels to put in the rows.
  475.  
  476. If you don't want libpng to handle the interlacing details, just call
  477. png_read_rows() seven times to read in all seven images.  Each of the
  478. images are valid images by themselves, or they can be combined on an
  479. 8x8 grid to form a single image (although if you intend to combine them
  480. you would be far better off using the libpng interlace handling).
  481.  
  482. The first pass will return an image 1/8 as wide as the entire image
  483. (every 8th column starting in column 0) and 1/8 as high as the original
  484. (every 8th row starting in row 0), the second will be 1/8 as wide
  485. (starting in column 4) and 1/8 as high (also starting in row 0).  The
  486. third pass will be 1/4 as wide (every 4th pixel starting in row 0) and
  487. 1/8 as high (every 8th row starting in row 4), and the fourth pass will
  488. be 1/4 as wide and 1/4 as high (every 4th column starting in column 2,
  489. and every 4th row starting in row 0).  The fifth pass will return an
  490. image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2),
  491. while the sixth pass will be 1/2 as wide and 1/2 as high as the original
  492. (starting in column 1 and row 0).  The seventh and final pass will be as
  493. wide as the original, and 1/2 as high, containing all of the odd
  494. numbered scanlines.  Phew!
  495.  
  496. If you want libpng to expand the images, call this before calling
  497. png_start_read_image() or png_read_update_info():
  498.  
  499.     if (info_ptr->interlace_type)
  500.         number_passes = png_set_interlace_handling(png_ptr);
  501.  
  502. This will return the number of passes needed.  Currently, this
  503. is seven, but may change if another interlace type is added.
  504. This function can be called even if the file is not interlaced,
  505. where it will return one pass.
  506.  
  507. If you are not going to display the image after each pass, but are
  508. going to wait until the entire image is read in, use the sparkle
  509. effect.  This effect is faster and the end result of either method
  510. is exactly the same.  If you are planning on displaying the image
  511. after each pass, the rectangle effect is generally considered the
  512. better looking one.
  513.  
  514. If you only want the "sparkle" effect, just call png_read_rows() as
  515. normal, with the third parameter NULL.  Make sure you make pass over
  516. the image number_passes times, and you don't change the data in the
  517. rows between calls.  You can change the locations of the data, just
  518. not the data.  Each pass only writes the pixels appropriate for that
  519. pass, and assumes the data from previous passes is still valid.
  520.  
  521.     png_read_rows(png_ptr, row_pointers, NULL, number_of_rows);
  522.  
  523. If you only want the first effect (the rectangles), do the same as
  524. before except pass the row buffer in the third parameter, and leave
  525. the second parameter NULL.
  526.  
  527.     png_read_rows(png_ptr, NULL, row_pointers, number_of_rows);
  528.  
  529. After you are finished reading the image, you can finish reading
  530. the file.  If you are interested in comments or time, which may be
  531. stored either before or after the image data, you should pass the
  532. info_ptr pointer from the png_read_info() call, or you can pass a
  533. separate png_info struct if you want to keep the comments from
  534. before and after the image separate.  If you are not interested, you
  535. can pass NULL.
  536.  
  537.    png_read_end(png_ptr, end_info);
  538.  
  539. When you are done, you can free all memory allocated by libpng like this:
  540.  
  541.    png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  542.  
  543. For a more compact example of reading a PNG image, see the file example.c.
  544.  
  545.  
  546. Reading PNG files progressively:
  547.  
  548. The progressive reader is slightly different then the non-progressive
  549. reader.  Instead of calling png_read_info(), png_read_rows(), and
  550. png_read_end(), you make one call to png_process_data(), which calls
  551. callbacks when it has the info, a row, or the end of the image.  You
  552. set up these callbacks with png_set_progressive_read_fn().  You don't
  553. have to worry about the input/output functions of libpng, as you are
  554. giving the library the data directly in png_process_data().  I will
  555. assume that you have read the section on reading PNG files above,
  556. so I will only highlight the differences (although I will show
  557. all of the code).
  558.  
  559. png_structp png_ptr;
  560. png_infop info_ptr;
  561.  
  562. /*  An example code fragment of how you would initialize the progressive
  563.     reader in your application. */
  564. int
  565. initialize_png_reader()
  566. {
  567.     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  568.         (void *)user_error_ptr, user_error_fn, user_warning_fn);
  569.     if (!png_ptr)
  570.         return -1;
  571.     info_ptr = png_create_info_struct(png_ptr);
  572.     if (!info_ptr)
  573.     {
  574.         png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
  575.         return -1;
  576.     }
  577.  
  578.     if (setjmp(png_ptr->jmpbuf))
  579.     {
  580.         png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
  581.         return -1;
  582.     }
  583.  
  584.     /* This one's new.  You can provide functions to be called
  585.        when the header info is valid, when each row is completed,
  586.        and when the image is finished.  If you aren't using all
  587.        functions, you can specify a NULL parameter.  You can use
  588.        any struct as the user_ptr (cast to a void pointer for the
  589.        function call), and retrieve the pointer from inside the
  590.        callbacks using the function png_get_progressive_ptr(png_ptr);        
  591.        which will return a void pointer, which you have to cast
  592.        appropriately.
  593.      */
  594.     png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
  595.         info_callback, row_callback, end_callback);
  596.  
  597.     return 0;
  598. }
  599.  
  600. /* A code fragment that you call as you recieve blocks of data */
  601. int
  602. process_data(png_bytep buffer, png_uint_32 length)
  603. {
  604.     if (setjmp(png_ptr->jmpbuf))
  605.     {
  606.         png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
  607.         return -1;
  608.     }
  609.  
  610.     /* This one's new also.  Simply give it a chunk of data
  611.        from the file stream (in order, of course).  On machines
  612.        with segmented memory models machines, don't give it any 
  613.        more than 64K.  The library seems to run fine with sizes 
  614.        of 4K. Although you can give it much less if necessary 
  615.        (I assume you can give it chunks of 1 byte, I haven't
  616.        tried less then 256 bytes yet).  When this function returns,
  617.        you may want to display any rows that were generated in the
  618.        row callback if you don't already do so there. 
  619.      */
  620.     png_process_data(png_ptr, info_ptr, buffer, length);
  621.     return 0;
  622. }
  623.  
  624. /* This function is called (as set by png_set_progressive_fn() above)
  625.    when enough data has been supplied so all of the header has been read.
  626.  */
  627. void
  628. info_callback(png_structp png_ptr, png_infop info)
  629. {
  630.     /* Do any setup here, including setting any of the transformations
  631.        mentioned in the Reading PNG files section.  For now, you _must_
  632.        call either png_start_read_image() or png_read_update_info()
  633.        after all the transformations are set (even if you don't set
  634.        any).  You may start getting rows before png_process_data()
  635.        returns, so this is your last chance to prepare for that.
  636.      */
  637. }
  638.  
  639. /* This function is called when each row of image data is complete */
  640. void
  641. row_callback(png_structp png_ptr, png_bytep new_row,
  642.     png_uint_32 row_num, int pass)
  643. {
  644.     /* If the image is interlaced, and you turned on the interlace
  645.        handler, this function will be called for every row in every pass.
  646.        Some of these rows will not be changed from the previous pass.
  647.        When the row is not changed, the new_row variable will be NULL.
  648.        The rows and passes are called in order, so you don't really
  649.        need the row_num and pass, but I'm supplying them because it
  650.        may make your life easier.
  651.  
  652.        For the non-NULL rows of interlaced images, you must call
  653.        png_progressive_combine_row() passing in the row and the
  654.        old row.  You can call this function for NULL rows (it will
  655.        just return) and for non-interlaced images (it just does the
  656.        memcpy for you) if it will make the code easier.  Thus, you
  657.        can just do this for all cases:
  658.      */
  659.  
  660.         png_progressive_combine_row(png_ptr, old_row, new_row);
  661.  
  662.     /* where old_row is what was displayed for previous rows.  Note
  663.        that the first pass (pass == 0, really) will completely cover
  664.        the old row, so the rows do not have to be initialized.  After
  665.        the first pass (and only for interlaced images), you will have
  666.        to pass the current row, and the function will combine the
  667.        old row and the new row.
  668.     */  
  669. }
  670.  
  671. void
  672. end_callback(png_structp png_ptr, png_infop info)
  673. {
  674.     /* This function is called after the whole image has been read,
  675.        including any chunks after the image (up to and including
  676.        the IEND).  You will usually have the same info chunk as you
  677.        had in the header, although some data may have been added
  678.        to the comments and time fields.
  679.  
  680.        Most people won't do much here, perhaps setting a flag that
  681.        marks the image as finished.
  682.      */
  683. }
  684.  
  685.  
  686.  
  687. IV. Writing
  688.  
  689. Much of this is very similar to reading.  However, everything of
  690. importance is repeated here, so you won't have to constantly look
  691. back up in the reading section to understand writing.
  692.  
  693. You will want to do the I/O initialization before you get into libpng,
  694. so if it doesn't work, you don't have anything to undo. If you are not
  695. using the standard I/O functions, you will need to replace them with
  696. custom writing functions.  See the discussion under Customizing libpng.
  697.     
  698.     FILE *fp = fopen(file_name, "wb");
  699.     if (!fp)
  700.     {
  701.        return;
  702.     }
  703.  
  704. Next, png_struct and png_info need to be allocated and initialized.
  705. As these can be both relatively large, you may not want to store these
  706. on the stack, unless you have stack space to spare.  Of course, you
  707. will want to check if they return NULL.
  708.  
  709.     png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  710.        (void *)user_error_ptr, user_error_fn, user_warning_fn);
  711.     if (!png_ptr)
  712.        return;
  713.  
  714.     png_infop info_ptr = png_create_info_struct(png_ptr);
  715.     if (!info_ptr)
  716.     {
  717.        png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
  718.        return;
  719.     }
  720.  
  721. After you have these structures, you will need to set up the
  722. error handling.  When libpng encounters an error, it expects to
  723. longjmp() back to your routine.  Therefore, you will need to call
  724. setjmp and pass the jmpbuf field of your png_struct.  If you
  725. write the file from different routines, you will need to update
  726. the jmpbuf field every time you enter a new routine that will
  727. call a png_ function.  See your documentation of setjmp/longjmp
  728. for your compiler for more information on setjmp/longjmp.  See
  729. the discussion on libpng error handling in the Customizing Libpng
  730. section below for more information on the libpng error handling.
  731.     
  732.     if (setjmp(png_ptr->jmpbuf))
  733.     {    
  734.         png_destroy_write_struct(&png_ptr, &info_ptr);
  735.         fclose(fp);
  736.         return;
  737.     }
  738.  
  739. Now you need to set up the input code.  The default for libpng is to
  740. use the C function fwrite().  If you use this, you will need to pass a
  741. valid FILE * in the function png_init_io().  Be sure that the file is
  742. opened in binary mode.  Again, if you wish to handle writing data in
  743. another way, see the discussion on libpng I/O handling in the Customizing
  744. Libpng section below.
  745.  
  746.     png_init_io(png_ptr, fp);
  747.  
  748. You now have the option of modifying how the compression library will
  749. run.  The following functions are mainly for testing, but may be useful
  750. in some cases, like if you need to write png files extremely fast and
  751. are willing to give up some compression, or if you want to get the
  752. maximum possible compression at the expense of slower writing.  If you
  753. have no special needs in this area, let the library do what it wants by
  754. not calling this function at all, as it has been tuned to deliver a good
  755. speed/compression ratio. The second parameter to png_set_filter() is
  756. the filter method, for which the only valid value is '0' (as of the
  757. 06/96 PNG specification.  The third parameter is a flag that indicates
  758. which filter type(s) are to be tested for each scanline.  See the
  759. Compression Library for details on the specific filter types.
  760.  
  761.     
  762.     /* turn on or off filtering, and/or choose specific filters */
  763.     png_set_filter(png_ptr, 0,
  764.        PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_PAETH);
  765.  
  766. The png_set_compression_???() functions interface to the zlib compression
  767. library, and should mostly be ignored unless you really know what you are
  768. doing.  The only generally useful call is png_set_compression_level()
  769. which changes how much time zlib spends on trying to compress the image
  770. data.  See the Compression Library for details on the compression levels.
  771.  
  772.     /* set the zlib compression level */
  773.     png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
  774.  
  775.     /* set other zlib parameters */
  776.     png_set_compression_mem_level(png_ptr, 8);
  777.     png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
  778.     png_set_compression_window_bits(png_ptr, 15);
  779.     png_set_compression_method(png_ptr, 8);
  780.  
  781. You now need to fill in the png_info structure with all the data you
  782. wish to write before the actual image.  Note that the only thing you
  783. are allowed to write after the image is the text chunks and the time
  784. chunk (as of PNG Specification 1.0, anyway).  See png_write_end() and
  785. the latest PNG specification for more information on that.  If you
  786. wish to write them before the image, fill them in now, and flag that
  787. data as being valid.  If you want to wait until after the data, don't
  788. fill them until png_write_end().  For all the fields in png_info and
  789. their data types, see png.h.  For explanations of what the fields
  790. contain, see the PNG specification.
  791.  
  792. Some of the more important parts of the png_info are:
  793.  
  794.     width          - holds the width of the file
  795.     height         - holds the height of the file
  796.     bit_depth      - holds the bit depth of one of the image channels
  797.     color_type     - describes the channels and what they mean
  798.                      see the PNG_COLOR_TYPE_ defines for more information
  799.     interlace_type - allowed values are 0 for none, 1 for interlaced
  800.     valid          - this describes which optional chunks to write to the
  801.                      file.  Note that if you are writing a
  802.                      PNG_COLOR_TYPE_PALETTE file, the PLTE chunk is not
  803.                      optional, but must still be marked for writing.  To
  804.                      mark chunks for writing, logical OR '|' valid with
  805.                      the appropriate PNG_INFO_<chunk name> define.
  806.     palette        - the palette for the file (PNG_INFO_PLTE)
  807.     num_palette    - number of entries in the palette
  808.     gamma          - the gamma the file is written at (PNG_INFO_gAMA)
  809.     sig_bit        - the number of significant bits (PNG_INFO_sBIT)
  810.                      for the gray, red, green, and blue channels, whichever
  811.                      are appropriate for the given color type.
  812.     trans_values   - transparent pixel for non-paletted images (PNG_INFO_tRNS)
  813.     trans          - array of transparent entries for paletted images
  814.     num_trans      - number of transparent entries
  815.     hist           - histogram of palette (PNG_INFO_hIST)
  816.     mod_time       - time image was last modified (PNG_VALID_tIME)
  817.     background     - background color (PNG_VALID_bKGD)
  818.     text           - text comments in the file.
  819.     num_text       - number of comments
  820.  
  821. A quick word about text and num_text.  text is an array of png_text
  822. structures.  num_text is the number of valid structures in the array.
  823. If you want, you can use max_text to hold the size of the array, but
  824. libpng ignores it for writing (it does use it for reading).  Each
  825. png_text structure holds a keyword-text value, and a compression type.
  826. The compression types have the same valid numbers as the compression
  827. types of the image data.  Currently, the only valid number is zero.
  828. However, you can store text either compressed or uncompressed, unlike
  829. images which always have to be compressed.  So if you don't want the
  830. text compressed, set the compression type to -1.  Until text gets
  831. around 1000 bytes, it is not worth compressing it.
  832.  
  833. The keywords that are given in the PNG Specification are:
  834.  
  835.             Title            Short (one line) title or caption for image
  836.             Author           Name of image's creator
  837.             Description      Description of image (possibly long)
  838.             Copyright        Copyright notice
  839.             Creation Time    Time of original image creation
  840.             Software         Software used to create the image
  841.             Disclaimer       Legal disclaimer
  842.             Warning          Warning of nature of content
  843.             Source           Device used to create the image
  844.             Comment          Miscellaneous comment; conversion from other
  845.                              image format
  846.  
  847. The keyword-text pairs work like this.  Keywords should be short
  848. simple descriptions of what the comment is about.  Some typical
  849. keywords are found in the PNG specification, as is some recomendations
  850. on keywords.  You can repeat keywords in a file.  You can even write
  851. some text before the image and some after.  For example, you may want
  852. to put a description of the image before the image, but leave the
  853. disclaimer until after, so viewers working over modem connections
  854. don't have to wait for the disclaimer to go over the modem before
  855. they start seeing the image.  Finally, keywords should be full
  856. words, not abbreviations.  Keywords and text are in the ISO 8859-1
  857. (Latin-1) character set (a superset of regular ASCII) and can not
  858. contain NUL characters, and should not contain control or other
  859. unprintable characters.  To make the comments widely readable, stick
  860. with basic ASCII, and avoid machine specific character set extensions
  861. like the IBM-PC character set.  The keyword must be present, but
  862. you can leave off the text string on non-compressed pairs.
  863. Compressed pairs must have a text string, as only the text string
  864. is compressed anyway, so the compression would be meaningless.
  865.  
  866. PNG supports modification time via the png_time structure.  Two
  867. conversion routines are proved, png_convert_from_time_t() for
  868. time_t and png_convert_from_struct_tm() for struct tm.  The
  869. time_t routine uses gmtime().  You don't have to use either of
  870. these, but if you wish to fill in the png_time structure directly,
  871. you should provide the time in universal time (GMT) if possible
  872. instead of your local time.  Note that the year number is the full
  873. year (ie 1996, rather than 96), and that months start with 1.
  874.  
  875. You are now ready to write all the file information up to the actual
  876. image data.  You do this with a call to png_write_info().
  877.  
  878.     png_write_info(png_ptr, info_ptr);
  879.  
  880. After you've written the file information, you can set up the library
  881. to handle any special transformations of the image data.  The various
  882. ways to transform the data will be described in the order that they
  883. should occur.  This is important, as some of these change the color
  884. type and/or bit depth of the data, and some others only work on
  885. certain color types and bit depths.  Even though each transformation
  886. checks to see if it has data that it can do somthing with, you should
  887. make sure to only enable a transformation if it will be valid for the
  888. data.  For example, don't swap red and blue on grayscale data.
  889.  
  890. PNG files store RGB pixels packed into 3 bytes.  This code tells
  891. the library to expect input data with 4 bytes per pixel
  892.  
  893.     png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  894.  
  895. where the 0 is the value that will be put in the 4th byte, and the
  896. location is either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending
  897. upon whether the filler byte is stored XRGB or RGBX.
  898.  
  899. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  900. they can, resulting in, for example, 8 pixels per byte for 1 bit files.
  901. If the data is supplied at 1 pixel per byte, use this code, which will
  902. correctly pack the pixels into a single byte:
  903.  
  904.     png_set_packing(png_ptr);
  905.  
  906. PNG files reduce possible bit depths to 1, 2, 4, 8, and 16.  If your
  907. data is of another bit depth, you can write an sBIT chunk into the
  908. file so that decoders can get the original data if desired.
  909.     
  910.     /* Do this before png_write_info() */
  911.     info_ptr->valid |= PNG_INFO_sBIT;
  912.  
  913.     /* Set the true bit depth of the image data */
  914.     if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  915.     {
  916.         info_ptr->sig_bit.red = true_bit_depth;
  917.         info_ptr->sig_bit.green = true_bit_depth;
  918.         info_ptr->sig_bit.blue = true_bit_depth;
  919.     }
  920.     else
  921.     {
  922.         info_ptr->sig_bit.gray = true_bit_depth;
  923.     }
  924.  
  925.     if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  926.     {
  927.         info_ptr->sig_bit.alpha = true_bit_depth;
  928.     }
  929.  
  930. If the data is stored in the row buffer in a bit depth other than
  931. one supported by PNG (ie 3 bit data in the range 0-7 for a 4-bit PNG),
  932. this will scale the values to appear to be the correct bit depth as
  933. is required by PNG.
  934.  
  935.     png_set_shift(png_ptr, &(info_ptr->sig_bit));
  936.  
  937. PNG files store 16 bit pixels in network byte order (big-endian,
  938. ie. most significant bits first).  This code would be used if they are
  939. supplied the other way (little-endian, ie. least significant bits
  940. first, eg. the way PCs store them):
  941.  
  942.     png_set_swap(png_ptr);
  943.  
  944. PNG files store 3 color pixels in red, green, blue order.  This code
  945. would be used if they are supplied as blue, green, red:
  946.  
  947.     png_set_bgr(png_ptr);
  948.  
  949. PNG files describe monochrome as black being zero and white being
  950. one. This code would be used if the pixels are supplied with this reversed
  951. (black being one and white being zero):
  952.  
  953.     png_set_invert(png_ptr);
  954.  
  955. It is possible to have libpng flush any pending output, either manually,
  956. or automatically after a certain number of lines have been written.  To
  957. flush the output stream a single time call:
  958.  
  959.     png_write_flush(png_ptr);
  960.  
  961. and to have libpng flush the output stream periodically after a certain
  962. number of scanlines have been written, call:
  963.  
  964.     png_set_flush(png_ptr, nrows);
  965.  
  966. Note that the distance between rows is from the last time png_write_flush()
  967. was called, or the first row of the image if it has never been called.
  968. So if you write 50 lines, and then png_set_flush 25, it will flush the
  969. output on the next scanline, and every 25 lines thereafter, unless
  970. png_write_flush()ls is called before 25 more lines have been written.
  971. If nrows is too small (less than about 10 lines for a 640 pixel wide
  972. RGB image) the image compression may decrease noticably (although this
  973. may be acceptable for real-time applications).  Infrequent flushing will
  974. only degrade the compression performance by a few percent over images
  975. that do not use flushing.
  976.  
  977. That's it for the transformations.  Now you can write the image data.
  978. The simplest way to do this is in one function call.  If have the
  979. whole image in memory, you can just call png_write_image() and libpng
  980. will write the image.  You will need to pass in an array of pointers to
  981. each row.  This function automatically handles interlacing, so you don't
  982. need to call png_set_interlace_handling() or call this function multiple
  983. times, or any of that other stuff necessary with png_write_rows().
  984.  
  985.     png_write_image(png_ptr, row_pointers);
  986.  
  987. where row_pointers is:
  988.  
  989.     png_bytef *row_pointers[height];
  990.  
  991. You can point to void or char or whatever you use for pixels.
  992.  
  993. If you can't want to write the whole image at once, you can
  994. use png_write_rows() instead.  If the file is not interlaced,
  995. this is simple:
  996.  
  997.     png_write_rows(png_ptr, row_pointers, number_of_rows);
  998.  
  999. row_pointers is the same as in the png_write_image() call.
  1000.  
  1001. If you are just writing one row at a time, you can do this with
  1002. row_pointers:
  1003.  
  1004.     png_bytep row_pointer = row;
  1005.  
  1006.     png_write_row(png_ptr, &row_pointer);
  1007.  
  1008. When the file is interlaced, things can get a good deal more
  1009. complicated.  The only currently (as of 6/96 -- PNG Specification
  1010. version 1.0) defined interlacing scheme for PNG files is a
  1011. compilcated interlace scheme, known as Adam7, that breaks down an
  1012. image into seven smaller images of varying size.  libpng will build
  1013. these images for you, or you can do them yourself.  If you want to
  1014. build them yourself, see the PNG specification for details of which
  1015. pixels to write when.
  1016.  
  1017. If you don't want libpng to handle the interlacing details, just
  1018. use png_set_interlace_handling() and call png_write_rows() the
  1019. correct number of times to write all seven sub-images.
  1020.  
  1021. If you want libpng to build the sub-images, call this before you start
  1022. writing any rows:
  1023.  
  1024.     number_passes = png_set_interlace_handling(png_ptr);
  1025.  
  1026. This will return the number of passes needed.  Currently, this
  1027. is seven, but may change if another interlace type is added.
  1028.  
  1029. Then write the complete image number_passes times.
  1030.  
  1031.     png_write_rows(png_ptr, row_pointers, number_of_rows);
  1032.  
  1033. As some of these rows are not used, and thus return immediately,
  1034. you may want to read about interlacing in the PNG specification,
  1035. and only update the rows that are actually used.
  1036.  
  1037. After you are finished writing the image, you should finish writing
  1038. the file.  If you are interested in writing comments or time, you should
  1039. pass the an appropriately filled png_info pointer.  If you
  1040. are not interested, you can pass NULL.  If you have written text at
  1041. the beginning and are not writing more at the end, you should set
  1042. info_ptr->num_text = 0, or the text will be written again here.
  1043.  
  1044.     png_write_end(png_ptr, info_ptr);
  1045.  
  1046. When you are done, you can free all memory used by libpng like this:
  1047.  
  1048.     png_destroy_write_struct(&png_ptr, &info_ptr);
  1049.  
  1050. You must free any data you allocated for info_ptr, such as comments,
  1051. palette, or histogram, before the call to png_destroy_write_struct();
  1052.  
  1053. For a more compact example of writing a PNG image, see the file example.c.
  1054.  
  1055.  
  1056. V. Modifying/Customizing libpng:
  1057.  
  1058. There are two issues here.  The first is changing how libpng does
  1059. standard things like memory allocation, input/output, and error handling.
  1060. The second deals with more complicated things like adding new chunks,
  1061. adding new transformations, and generally changing how libpng works.
  1062.  
  1063. All of the memory allocation, input/output, and error handling in
  1064. libpng goes through callbacks which are user setable.  The default
  1065. routines are in pngmem.c, pngrio.c, pngwio.c, and pngerror.c respectively.
  1066. To change these functions, call the approprate png_set_???_fn() function.
  1067.  
  1068. Memory allocation is done through the functions png_large_malloc(),
  1069. png_malloc(), png_realloc(), png_large_free(), and png_free().  These
  1070. currently just call the standard C functions.  The large functions must
  1071. handle exactly 64K, but they don't have to handle more than that.  If
  1072. your pointers can't access more then 64K at a time, you will want to
  1073. set MAXSEG_64K in zlib.h.  Since it is unlikely that the method of
  1074. handling memory allocation on a platform will change between applications,
  1075. these functions must be modified in the library at compile time.
  1076.  
  1077. Input/Output in libpng is done throught png_read() and png_write(), which
  1078. currently just call fread() and fwrite().  The FILE * is stored in
  1079. png_struct, and is initialized via png_init_io().  If you wish to change
  1080. the method of I/O, the library supplies callbacks that you can set through
  1081. the function png_set_read_fn() and png_set_write_fn() at run time.  These
  1082. functions also provide a void pointer that can be retrieved via the function
  1083. png_get_io_ptr().  For example:
  1084.  
  1085.     png_set_read_fn(png_structp png_ptr, voidp io_ptr,
  1086.         png_rw_ptr read_data_fn)
  1087.  
  1088.     png_set_write_fn(png_structp png_ptr, voidp io_ptr,
  1089.         png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn);
  1090.  
  1091.     voidp io_ptr = png_get_io_ptr(png_ptr);
  1092.  
  1093. The replacement I/O functions should have prototypes as follows:
  1094.  
  1095.     void user_read_data(png_structp png_ptr, png_bytep data,
  1096.         png_uint_32 length);
  1097.     void user_write_data(png_structp png_ptr, png_bytep data,
  1098.         png_uint_32 length);
  1099.     void user_flush_data(png_structp png_ptr);
  1100.  
  1101. Supplying NULL for the read, write, or flush functions sets them back
  1102. to using the default C stream functions.  It is an error to read from
  1103. a write stream, and vice versa.
  1104.  
  1105. Error handling in libpng is done through png_error() and png_warning().
  1106. Errors handled through png_error() are fatal, meaning that png_error()
  1107. should never return to it's caller.  Currently, this is handled via
  1108. setjmp() and longjmp(), but you could change this to do things like
  1109. exit() if you should wish.  On non-fatal errors, png_warning() is called
  1110. to print a warning message, and then control returns to the calling code.
  1111. By default png_error() and png_warning() print a message on stderr via
  1112. fprintf() unless the library is compiled with PNG_NO_STDIO defined.  If
  1113. you wish to change the behavior of the error functions, you will need to
  1114. set up your own message callbacks.  These functions are normally supplied
  1115. at the time that the png_struct is created.  It is also possible to change
  1116. these functions after png_create_???_struct() has been called by calling:
  1117.  
  1118.     png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  1119.         png_error_ptr error_fn, png_error_ptr warning_fn);
  1120.  
  1121.     png_voidp error_ptr = png_get_error_ptr(png_ptr);
  1122.  
  1123. If NULL is supplied for either error_fn or warning_fn, then the libpng
  1124. default function will be used, calling fprintf() and/or longjmp() if a
  1125. problem is encountered.  The replacement error functions should have
  1126. parameters as follows:
  1127.  
  1128.     void user_error_fn(png_struct png_ptr, png_const_charp error_msg);
  1129.     void user_warning_fn(png_struct png_ptr, png_const_charp warning_msg);
  1130.  
  1131. The motivation behind using setjmp() and longjmp() is the C++ throw and
  1132. catch exception handling methods.  This makes the code much easier to write,
  1133. as there is no need to check every return code of every function call.
  1134. However, there are some uncertainties about the status of local variables
  1135. after a longjmp, so the user may want to be careful about doing anything after
  1136. setjmp returns non zero besides returning itself.  Consult your compiler
  1137. documentation for more details.
  1138.  
  1139. If you need to read or write custom chunks, you will need to get deeper
  1140. into the libpng code, as a mechanism has not yet been supplied for user
  1141. callbacks with custom chunks.  First, read the PNG specification, and have
  1142. a first level of understanding of how it works.  Pay particular attention
  1143. to the sections that describe chunk names, and look at how other chunks
  1144. were designed, so you can do things similarly.  Second, check out the
  1145. sections of libpng that read and write chunks.  Try to find a chunk that
  1146. is similar to yours and copy off of it.  More details can be found in the
  1147. comments inside the code.  A way of handling unknown chunks in a generic
  1148. method, potentially via callback functions, would be best.
  1149.  
  1150. If you wish to write your own transformation for the data, look through
  1151. the part of the code that does the transformations, and check out some of
  1152. the simpler ones to get an idea of how they work.  Try to find a similar
  1153. transformation to the one you want to add and copy off of it.  More details
  1154. can be found in the comments inside the code itself.
  1155.  
  1156. Configuring for 16 bit platforms:
  1157.  
  1158. You may need to change the png_large_malloc() and png_large_free()
  1159. routines in pngmem.c, as these are requred to allocate 64K, although
  1160. there is already support for many of the common DOS compilers.  Also,
  1161. you will want to look into zconf.h to tell zlib (and thus libpng) that
  1162. it cannot allocate more then 64K at a time.  Even if you can, the memory
  1163. won't be accessable.  So limit zlib and libpng to 64K by defining MAXSEG_64K.
  1164.  
  1165. Configuring for DOS:
  1166.  
  1167. For DOS users which only have access to the lower 640K, you will
  1168. have to limit zlib's memory usage via a png_set_compression_mem_level()
  1169. call.  See zlib.h or zconf.h in the zlib library for more information.
  1170.  
  1171. Configuring for Medium Model:
  1172.  
  1173. Libpng's support for medium model has been tested on most of the popular
  1174. complers.  Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
  1175. defined, and FAR gets defined to far in pngconf.h, and you should be
  1176. all set.  Everything in the library (except for zlib's structure) is
  1177. expecting far data.  You must use the typedefs with the p or pp on
  1178. the end for pointers (or at least look at them and be careful).  Make
  1179. note that the row's of data are defined as png_bytepp which is a
  1180. unsigned char far * far *.
  1181.  
  1182. Configuring for gui/windowing platforms:
  1183.  
  1184. You will need to write new error and warning functions that use the GUI
  1185. interface, as described previously, and set them to be the error and
  1186. warning functions at the time that png_create_???_struct() is called,
  1187. in order to have them available during the structure initialization.
  1188. They can be changed later via png_set_error_fn().  On some compliers,
  1189. you may also have to change the memory allocators (png_malloc, etc.).
  1190.  
  1191. Configuring for compiler xxx:
  1192.  
  1193. All includes for libpng are in pngconf.h.  If you need to add/change/delete
  1194. an include, this is the place to do it.  The includes that are not
  1195. needed outside libpng are protected by the PNG_INTERNAL definition,
  1196. which is only defined for those routines inside libpng itself.  The
  1197. files in libpng proper only include png.h, which includes pngconf.h.
  1198.  
  1199. Configuring zlib:
  1200.  
  1201. There are special functions to configure the compression.  Perhaps the
  1202. most useful one changes the compression level, which currently uses
  1203. input compression values in the range 0 - 9.  The library normally
  1204. uses the default compression level (Z_DEFAULT_COMPRESSION = 6), but if
  1205. speed is not critical it is possible to configure it for maximum
  1206. compression (Z_BEST_COMPRESSION = 9) to generate smaller PNG files.
  1207. For online applications it may be desirable to have maximum speed
  1208. (Z_BEST_SPEED = 1).  With versions of zlib after v0.99, you can also
  1209. specify no compression (Z_NO_COMPRESSION = 0), but this would create
  1210. files larger than just storing the raw bitmap.  You can specify the
  1211. compression level by calling:
  1212.  
  1213.     png_set_compression_mem_level(png_ptr, level);
  1214.  
  1215. Another useful one is to reduce the memory level used by the library.
  1216. The memory level defaults to 8, but it can be lowered if you are
  1217. short on memory (running DOS, for example, where you only have 640K).
  1218.  
  1219.     png_set_compression_mem_level(png_ptr, level);
  1220.  
  1221. If you want to control whether libpng uses filtering or not, you
  1222. can call this function.  Filtering is enabled by default for RGB
  1223. and grayscale images (with and without alpha), and for 8-bit
  1224. paletted images, but not for paletted images with bit depths less
  1225. than 8 bits/pixel.  The 'method' parameter sets the main filtering
  1226. method, which is currently only '0' in the PNG 1.0 specification.
  1227. The 'filters' parameter sets which filter(s), if any, should be
  1228. used for each scanline.  Possible values are PNG_ALL_FILTERS and
  1229. PNG_NO_FILTERS to turn filtering on and off, respectively.
  1230. Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
  1231. PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
  1232. ORed together '|' to specify one or more filters to use.  These
  1233. filters are described in more detail in the PNG specification.  If
  1234. you intend to change the filter type during the course of writing
  1235. the image, you should start with flags set for all of the filters
  1236. you intend to use so that libpng can initialize its internal
  1237. structures appropriately for all of the filter types.
  1238.  
  1239.     png_set_filter(png_ptr, method, filters);
  1240.  
  1241. The other functions are for configuring zlib.  They are not recommended
  1242. for normal use and may result in writing an invalid PNG file.  See
  1243. zlib.h for more information on what these mean.
  1244.  
  1245.     png_set_compression_strategy(png_ptr, strategy);
  1246.     png_set_compression_window_bits(png_ptr, window_bits);
  1247.     png_set_compression_method(png_ptr, method);
  1248.  
  1249. Except for png_set_filter(), all of these are just controlling zlib,
  1250. so see the zlib documentation (zlib.h and zconf.h) for more information.
  1251.  
  1252. Removing unwanted object code:
  1253.  
  1254. There are a bunch of #define's in pngconf.h that control what parts of
  1255. libpng are compiled.  All the defines end in _SUPPORT.  If you are
  1256. never going to use an ability, you can change the #define to #undef
  1257. before recompiling libpng and save yourself code and data space.  All
  1258. the reading and writing specific code are in seperate files, so the
  1259. linker should only grab the files it needs.  However, if you want to
  1260. make sure, or if you are building a stand alone library, all the
  1261. reading files start with pngr and all the writing files start with
  1262. pngw.  The files that don't match either (like png.c, pngtrans.c, etc.)
  1263. are used for both reading and writing, and always need to be included.
  1264. The progressive reader is in pngpread.c
  1265.  
  1266. If you are creating or distributing a dynamically linked library (a .so
  1267. or DLL file), you should not remove or disable any parts of the
  1268. library, as this will cause applications linked with different versions
  1269. of the library to fail if they call functions not available in your
  1270. library.  The size of the library itself should not be an issue, because
  1271. only those sections which are actually used will be loaded into memory.
  1272.  
  1273. Changes to Libpng from version 0.88 to version 0.89
  1274.  
  1275. It should be noted that version 0.89 of libpng is not distributed by
  1276. the original author, Guy Schalnat, but rather Andreas Dilger, although
  1277. all of the copyright messages have been left in Guy's name.
  1278.  
  1279. The old libpng functions png_read_init(), png_write_init() and
  1280. png_info_init() still exist in the 0.89 version of the library, as
  1281. do png_read_destroy() and png_write_destroy().  The preferred method
  1282. of creating and initializing the libpng structures is via the
  1283. png_create_read_struct(), png_create_write_struct(), and
  1284. png_create_info_struct() because they isolate the size of the structures
  1285. from the application, allow version error checking, and also allow
  1286. the use of custom error handling routines during the initialization,
  1287. which the old functions do not.   The functions png_read_destroy() and
  1288. png_write_destroy() do not actually free the memory that libpng allocated
  1289. for these structs, but just reset the data structures, so they can be
  1290. used instead of png_destroy_read_struct() and png_destroy_write_struct()
  1291. if you feel there is too much system overhead allocating and freeing the
  1292. png_struct for each image read.
  1293.  
  1294. Setting the error callbacks via png_set_message_fn() before
  1295. png_read_init() as was suggested in libpng-0.88 is no longer supported
  1296. because this caused applications which do not use custom error functions
  1297. to fail if the png_ptr was not initialized to zero.  It is still possible
  1298. to set the error callbacks AFTER png_read_init(), or to change them with
  1299. png_set_error_fn(), which is essentially the same function, but with a
  1300. new name to force compilation errors with the new library.
  1301.  
  1302.